package com.xzzz.irda.guardcat.core.metric.memory;

import java.io.Serializable;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;

/**
 * Jvm 内存信息
 * -XX:+UseParallelGC -XX:+UseParallelOldGC -Xss512K -Xms1408M -Xmx1408M -XX:NewRatio=2 -XX:SurvivorRatio=8 -XX:MetaspaceSize=384M -XX:MaxMetaspaceSize=384M -XX:MaxDirectMemorySize=256M
 *
 * @author xzzz
 * @since 1.0.0
 */
public class JvmMemoryInfo implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 暂挂最终处理的对象数量
     * 被挂起以便回收的对象数
     */
    private int objectPendingFinalizationCount;

    /**
     * 堆内存使用信息
     */
    private BaseMemoryUsageInfo heapUsage;

    /**
     * 非堆内存使用信息
     */
    private BaseMemoryUsageInfo nonHeapUsage;

    /**
     * 构造器私有化
     */
    private JvmMemoryInfo() {
    }

    /**
     * 获取 JVM 内存信息
     *
     * @return JvmMemoryInfo  JVM 内存信息
     */
    public static JvmMemoryInfo getJvmMemoryInfo() {
        JvmMemoryInfo jvmMemoryInfo = new JvmMemoryInfo();

        MemoryMXBean memoryMxBean = ManagementFactory.getMemoryMXBean();

        jvmMemoryInfo.objectPendingFinalizationCount = memoryMxBean.getObjectPendingFinalizationCount();

        MemoryUsage heapMemoryUsage = memoryMxBean.getHeapMemoryUsage();
        UsageInfo heapUsageInfo = new UsageInfo(heapMemoryUsage.getInit(), heapMemoryUsage.getMax(), heapMemoryUsage.getCommitted(), heapMemoryUsage.getUsed());
        jvmMemoryInfo.heapUsage = new BaseMemoryUsageInfo("堆内存", heapUsageInfo);

        MemoryUsage nonHeapMemoryUsage = memoryMxBean.getNonHeapMemoryUsage();
        UsageInfo nonheapUsageInfo = new UsageInfo(nonHeapMemoryUsage.getInit(), nonHeapMemoryUsage.getMax(), nonHeapMemoryUsage.getCommitted(), nonHeapMemoryUsage.getUsed());
        jvmMemoryInfo.nonHeapUsage = new BaseMemoryUsageInfo("非堆内存", nonheapUsageInfo);


        return jvmMemoryInfo;
    }

    public int getObjectPendingFinalizationCount() {
        return objectPendingFinalizationCount;
    }

    public BaseMemoryUsageInfo getHeapUsage() {
        return heapUsage;
    }

    public BaseMemoryUsageInfo getNonHeapUsage() {
        return nonHeapUsage;
    }

    @Override
    public String toString() {
        return "Jvm 内存信息{" +
                "暂挂最终处理的对象数量=" + objectPendingFinalizationCount +
                ", 堆内存使用信息=" + heapUsage +
                ", 非堆内存使用信息=" + nonHeapUsage +
                '}';
    }
}
